/**********************************************************
 * AdminLoginInterceptor.java
 * Created by ankur
 * Last modified Date: Aug 26, 2008 8:30:56 AM by ankur
 * Version : 0.1
 * Copyright (c) 2008 - 2008 cyberThink Infotech Pvt. Ltd., All rights reserved.
 **********************************************************/

package com.printeverywhere.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.printeverywhere.util.AdminConstants;

/**
 * The Class SystemLockInterceptor.
 */
public class SystemLockInterceptor extends AbstractInterceptor implements
		StrutsStatics {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;
	
	/** The logger. */
	private static Logger logger = Logger.getLogger(SystemLockInterceptor.class);
	
	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	public String intercept(ActionInvocation invocation) throws Exception {
		if(logger.isInfoEnabled())
		logger.info("Starting System Interceptor".intern());
		synchronized (this) {
			// Get the action context from the invocation so we can access the
			// HttpServletRequest and HttpSession objects.
			final ActionContext context = invocation.getInvocationContext();
			HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
			HttpSession session = request.getSession(true);
			boolean systemaccess = (Boolean)session.getServletContext().getAttribute(AdminConstants.SYSTEM_ACCESS);
			if(!systemaccess){
				// Site is Temproarily OFF ?
				boolean adminAttempt = request.getRequestURL().toString().contains("admin".intern());
				if (adminAttempt) {
					if(logger.isInfoEnabled())
					logger.info("invoking Proxy ".intern() + invocation.getProxy().getActionName());
					return invocation.invoke();
				}
				if(logger.isInfoEnabled())
				logger.info("Returning to Login Page".intern());
				return "systemLock".intern();
			} else {
				return invocation.invoke();
			}
		}
	}
}